// pages/surveylist/surveylist.js
const app = getApp();
import API from "../../api/Api.js"
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isDone: false,
    pagination: {
      page: 1,
      limit: 10,
      pageCount: -1
    },
    loadMoreText: {
      more: "加载中",
      done: "没有更多"
    },
    loadMore: {
      show: false,
      text: "",
      loading: false
    },
    list: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let _that = this;
    _that.setData({
      isDone: !!(options.isdone * 1)
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let _that = this;
    _that.listSurveys();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    let _that = this;
    if (_that.data.pagination.pageCount >= 0 && _that.data.pagination.page >= _that.data.pagination.pageCount) {
      _that.setData({
        loadMore: {
          show: true,
          text: _that.data.loadMoreText.done,
          loading: false
        }
      });
      return;
    } else {
      _that.setData({
        loadMore: {
          show: true,
          text: _that.data.loadMoreText.more,
          loading: true
        }
      });
      setTimeout(() => {
        ++_that.data.pagination.page;
        _that.listSurveys();
      }, 1500);
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  /**
   * 列出列表
   */
  listSurveys() {
    let _that = this;
    _that.showLoading();
    let params = {
      isDone: _that.data.isDone,
      userId: app.globalData.userVo.id,
      page: _that.data.pagination.page,
      limit: _that.data.pagination.limit
    }
    API.survey.listSurveys(params).then(res => {
      if (!res || !res.total) {
        _that.resetLoadMoreData();
        _that.setData({
          list: [],
          'pagination.pageCount': 0
        });
        _that.hideLoading();
        return;
      }
      console.log(res);
      _that.data.list=[];
      _that.data.list.push(...res.rows);
      _that.setData({
        list: _that.data.list,
        'pagination.pageCount': res.pageCount
      });
      _that.resetLoadMoreData();
      _that.hideLoading();
    }).catch(() => {
      _that.resetLoadMoreData();
      _that.hideLoading();
    });
  },

  /**
   * 重置加载更多的数据
   */
  resetLoadMoreData() {
    let _that = this;
    _that.setData({
      loadMore: {
        show: false,
        text: "",
        loading: false
      }
    });
  },

  /**
   * 显示加载
   */
  showLoading() {
    let _that = this;
    wx.showLoading({
      title: '加载中',
    });
  },

  /**
   * 隐藏加载
   */
  hideLoading() {
    let _that = this;
    wx.hideLoading();
  }
})